package LinkedList;

public class DoubleLinkedListDemo {

  public static void main(String[] args) {

    //    创建节点
    HeroNode2 node1 = new HeroNode2(1, "will ospreay", "sky king");
    HeroNode2 node2 = new HeroNode2(2, "kenny omega", "best bout machine");
    HeroNode2 node3 = new HeroNode2(3, "kazuchika okada", "rainmaker");

    DoubleLinkedList doubleLinkedList = new DoubleLinkedList();

    doubleLinkedList.add(node1);
    doubleLinkedList.add(node2);
    doubleLinkedList.add(node3);

    doubleLinkedList.list();

//    修改节点
    System.out.println("修改后：");
    HeroNode2 node4 = new HeroNode2(2, "jay white", "switch blade");
    doubleLinkedList.update(node4);
    doubleLinkedList.list();

//    删除节点
    System.out.println("删除后：");
    doubleLinkedList.delete(2);
    doubleLinkedList.list();


  }
}

class DoubleLinkedList{
  //先初始化一个头节点,头节点不要动,不存放具体的数据
  private HeroNode2 head = new HeroNode2(0,"","");

  public HeroNode2 getHead() {
    return head;
  }

  public void list(){
//    若只有一个头结点，则直接返回
    if (head.next == null){
      System.out.println("链表为空");
      return;
    }
    HeroNode2 temp = head.next;
    while (true){
//      判断链表是否到最后
      if (temp == null){
        break;
      }
      System.out.println(temp);
//      输出完后要指向下一个节点
      temp = temp.next;
    }
  }

  public void add(HeroNode2 node){
//    添加的话要找到next为null的节点，将next修改为新添加的值
    HeroNode2 temp = head;
    while (true){
      if (temp.next == null){
        break;
      }
      temp = temp.next;
    }
    temp.next = node;
    node.pre = temp;
  }

  public void update(HeroNode2 newNode){
    boolean flag = false;
    HeroNode2 temp = head;

    while (true){
//      此时是最后一个
      if (temp.next == null){
        break;
      }
//      找到了，就是这个节点
      if (temp.no == newNode.no){
        flag = true;
        break;
      }
      temp = temp.next;
    }
    if (flag){
      temp.nickName = newNode.nickName;
      temp.name = newNode.name;
    }
  }

  //  找到删除节点的前一个
  public void delete(int no){

    if (head.next == null){
      System.out.println("链表为空");
      return;
    }

    HeroNode2 temp = head.next;
    boolean flag = false;

    while (true){

//      表示此时是最后一个节点
      if (temp == null){
        break;
      }
      if (temp.no == no){
        flag = true;
        break;
      }
      temp = temp.next;

    }
    if (flag){
      temp.pre.next = temp.next;
      if (temp.next != null){
        temp.next.pre = temp.pre;//如果不是最后一个节点，才执行这句话
      }
    }else {
      System.out.println("找不到该节点");
    }
  }
}

class HeroNode2{

  public String name;
  public String nickName;
  public int no;
  public HeroNode2 next;
  public HeroNode2 pre;

  public HeroNode2(int no,String name,String nickName){
    this.no = no;
    this.name = name;
    this.nickName = nickName;
  }

  @Override
  public String toString() {
    return "HeroNode2{" +
            "name='" + name + '\'' +
            ", nickName='" + nickName + '\'' +
            ", no=" + no + "}";
  }
}

